package com.edu.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/admin/*")
public class AdminAuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String path = req.getRequestURI();

        // 登录相关的请求和静态资源不需要验证
        if (path.endsWith("/admin/login") ||
                path.endsWith("/admin/login.jsp") ||
                path.contains("/static/")) {
            chain.doFilter(request, response);
            return;
        }

        // 验证session中是否有管理员信息
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("adminUser") != null) {
            chain.doFilter(request, response);
        } else {
            // 未登录则重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/admin/login.jsp");
        }
    }

    @Override
    public void destroy() {
    }
}